package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {


    @Autowired
    ApUserMapper apUserMapper;

    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //参数校验
        if (dto == null && StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //手机号登录
        if (StringUtils.isNotBlank(dto.getPhone()) &&StringUtils.isNotBlank(dto.getPassword())){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone())
                    .eq(ApUser::getStatus,0)
            );

            if (apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            String dbpsw = apUser.getPassword();
            String salt = apUser.getSalt();

            String psw = dto.getPassword();
            String npsw = salt + psw;
            String dpsw = DigestUtils.md5DigestAsHex(npsw.getBytes());
            if(!dbpsw.equals(dpsw)){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或者密码错误");
            }


            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("user",apUser);
            apUser.setPassword("");
            apUser.setSalt("");
            return ResponseResult.okResult(map);

        }else {//设备登录
            Map<String, Object> map = new HashMap<>();
//            map.put("token",AppJwtUtil.getToken(dto.getEquipmentId().longValue()));
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

        }
    }
}
